package com.wd.health.view.activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.wd.health.R;

import com.wd.health.model.adapter.AdvisoryPageMessageAdapter;
import com.wd.health.model.adapter.EmojiAdapter;
import com.wd.health.model.bean.DqwzBean;
import com.wd.health.model.bean.MyMessageBean;
import com.wd.health.model.bean.SendMessageBean;

import com.wd.health.utils.AudioRecoderUtils;
import com.wd.health.utils.RetrofitManager;
import com.wd.health.utils.RsaCoder;
import com.wd.health.view.widget.AudioRecoderDialog;


import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.content.CustomContent;
import cn.jpush.im.android.api.content.EventNotificationContent;
import cn.jpush.im.android.api.content.ImageContent;
import cn.jpush.im.android.api.content.PromptContent;
import cn.jpush.im.android.api.content.TextContent;
import cn.jpush.im.android.api.content.VoiceContent;
import cn.jpush.im.android.api.event.MessageEvent;
import cn.jpush.im.android.api.event.OfflineMessageEvent;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.api.BasicCallback;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class ConsultActivity extends AppCompatActivity implements View.OnClickListener,View.OnTouchListener, AudioRecoderUtils.OnAudioStatusUpdateListener {
    private Conversation singleConversation;
    private ImageView img_back;
    private TextView tv_consult_name;
    private RecyclerView rv_consult;
    private ImageView img_jianpan;
    private EditText et_context;
    private ImageView img_fasong;
    //appid
    private String APP_KEY = "b5f102cc307091e167ce52e0";
    private String ddd;
    private int recordId;
    private int id;
    private String s;
    private List<MyMessageBean> list = new ArrayList<>();
    private AdvisoryPageMessageAdapter advisoryPageMessageAdapter;
    private ImageView img_yuyin;
    private Button btn_context;
    private ImageView img_tupian;
    private AudioRecoderDialog recoderDialog;
    private AudioRecoderUtils recoderUtils;
    private long downT;
    protected static final int CHOOSE_PICTURE = 0;
    private static final int PHOTO_REQUEST_CAREMA = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果
    protected static Uri tempUri;
    private File tempFile;
    protected static final int TAKE_PICTURE = 1;
    private String doctorUserName;
    private static final String PHOTO_FILE_NAME = "temp_photo.png";
    private ImageView img_emoji;

    public final static List<String> emojis = new ArrayList<String>(){
        {
            add("😁");add("😂");add("😃");add("😄");add("😅");
            add("😆");add("😉");add("😊");add("😋");add("😌");
            add("😍");add("😏");add("😒");add("😓");add("😔");
            add("😖");add("😘");add("😚");add("😜");add("😝");
        }
    };
    private RelativeLayout rl_dibu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_consult);
        initView();
        JMessageClient.registerEventReceiver(ConsultActivity.this);
        initId();
        initData();
        initRv();
        initEmoji();
    }

    private void initEmoji() {
        img_emoji.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopup(v);
            }
        });
    }

    private void initRv() {
        advisoryPageMessageAdapter = new AdvisoryPageMessageAdapter(list, getApplicationContext());
        rv_consult.setAdapter(advisoryPageMessageAdapter);
    }


    private void initView() {
        img_back = findViewById(R.id.img_back);
        tv_consult_name = findViewById(R.id.tv_consult_name);
        rv_consult = findViewById(R.id.rv_consult);
        img_jianpan = findViewById(R.id.img_jianpan);
        et_context = findViewById(R.id.et_context);
        img_yuyin = findViewById(R.id.img_yuyin);
        btn_context = findViewById(R.id.btn_context);
        img_tupian = findViewById(R.id.img_tupian);
        img_fasong = findViewById(R.id.img_fasong);
        img_emoji = findViewById(R.id.img_emoji);
        rl_dibu = findViewById(R.id.rl_dibu);
        rv_consult.setLayoutManager(new LinearLayoutManager(this));
        btn_context.setOnTouchListener(this);
        recoderDialog = new AudioRecoderDialog(this);
        recoderDialog.setShowAlpha(0.98f);

        recoderUtils = new AudioRecoderUtils(new File(Environment.getExternalStorageDirectory() + "/recoder.amr"));
        recoderUtils.setOnAudioStatusUpdateListener(this);
        img_back.setOnClickListener(this);
        img_jianpan.setOnClickListener(this);
        img_yuyin.setOnClickListener(this);
        img_tupian.setOnClickListener(this);
        et_context.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length()>0){
                    img_fasong.setVisibility(View.VISIBLE);
                    img_tupian.setVisibility(View.GONE);
                }else {
                    img_fasong.setVisibility(View.GONE);
                    img_tupian.setVisibility(View.VISIBLE);
                }
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.img_back:
                finish();
                break;
            case R.id.img_jianpan:
                img_jianpan.setVisibility(View.GONE);
                img_yuyin.setVisibility(View.VISIBLE);
                et_context.setVisibility(View.VISIBLE);
                btn_context.setVisibility(View.GONE);
                break;
            case R.id.img_yuyin:
                img_yuyin.setVisibility(View.GONE);
                img_jianpan.setVisibility(View.VISIBLE);
                et_context.setVisibility(View.GONE);
                btn_context.setVisibility(View.VISIBLE);
                break;
            case R.id.img_tupian:
                showChoosePicDialog();
                break;

        }
    }
    private void showPopup(View v) {
        View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.div_pop, null);
        RecyclerView rv = view.findViewById(R.id.rv);
        rv.setLayoutManager(new GridLayoutManager(getApplicationContext(),5));
        EmojiAdapter emojiAdapter = new EmojiAdapter(emojis, getApplicationContext());
        rv.setAdapter(emojiAdapter);
        PopupWindow popupWindow = new PopupWindow(view,1100, 300, true);
        //事件
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });

        //设置背景
        popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.whiteback));
        //添加弹出、弹入的动画
        popupWindow.setAnimationStyle(R.style.Popupwindow);
        int[] location = new int[2];
        // 获得位置
        v.getLocationOnScreen(location);
        popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, (location[0] + v.getWidth() / 2) - 1100 / 2, location[1] - 300);
        emojiAdapter.setGetListener(new EmojiAdapter.GetListener() {
            @Override
            public void onClick(String emoji) {
                String s = et_context.getText().toString();
                et_context.setText(s+emoji);
                if (popupWindow.isShowing()){
                    popupWindow.dismiss();
                }
            }
        });

    }
    private void showChoosePicDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("发送图片");
        String[] items = { "选择本地照片", "拍照" };
        builder.setNegativeButton("取消", null);
        builder.setItems(items, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case CHOOSE_PICTURE: // 选择本地照片
                        Intent intent1 = new Intent(Intent.ACTION_PICK);
                        intent1.setType("image/*");
                        startActivityForResult(intent1, PHOTO_REQUEST_GALLERY);
                        break;
                    case TAKE_PICTURE: // 拍照
                        // 激活相机
                        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                        // 判断存储卡是否可以用，可用进行存储
                        if (hasSdcard()) {
                            tempFile = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
                            // 从文件中创建uri
                            Uri uri = Uri.fromFile(tempFile);
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                        }
                        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CAREMA
                        startActivityForResult(intent, PHOTO_REQUEST_CAREMA);
                        break;
                }
            }
        });
        builder.create().show();
    }

    /*
     * 判断sdcard是否被挂载
     */
    private boolean hasSdcard() {
        //判断ＳＤ卡手否是安装好的　　　media_mounted
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(data==null){
            return;
        }
        if (requestCode == PHOTO_REQUEST_GALLERY){
            if (data != null){
                // 得到图片的全路径
                Uri uri = data.getData();
                Log.e("TAG", "onActivityResult: "+uri );
                String[] proj = { MediaStore.Images.Media.DATA };

                Cursor actualimagecursor = managedQuery(uri,proj,null,null,null);

                int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

                actualimagecursor.moveToFirst();

                String img_path = actualimagecursor.getString(actual_image_column_index);

                File file = new File(img_path);

                try {
                    String username = RsaCoder.decryptByPublicKey(doctorUserName);
                    Message singleImageMessage = JMessageClient.createSingleImageMessage(username,APP_KEY, file);
                    JMessageClient.sendMessage(singleImageMessage);
                    singleImageMessage.setOnSendCompleteCallback(new ImageContent.CreateImageContentCallback() {
                        @Override
                        public void gotResult(int i, String s, ImageContent imageContent) {
                            if (i==0){
                                Log.e("TAG", "图片发送成功");
                                Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                                MyMessageBean myMessageBean3 = new MyMessageBean();
                                myMessageBean3.setBitmap(bitmap);
                                myMessageBean3.setType(3);
                                list.add(myMessageBean3);
                                advisoryPageMessageAdapter.notifyDataSetChanged();
                            }else {
                                Log.e("TAG", "图片发送失败");
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }else if (requestCode == PHOTO_REQUEST_CAREMA){
            // 从相机返回的数据
            if (hasSdcard()) {

            } else {
                Toast.makeText(ConsultActivity.this, "未找到存储卡，无法存储照片！", Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == PHOTO_REQUEST_CUT) {
            // 从剪切图片返回的数据
            if (data != null) {
                Bitmap bitmap = data.getParcelableExtra("data");
                //防止低版本没有办法获取数据，导致奔溃
                if(bitmap ==null){
                    return;
                }
                /**
                 * 获得图片
                 */
            }
            try {
                // 将临时文件删除
                tempFile.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void initId() {
        //获取咨询id
        RetrofitManager.getInstance().getDqwzData(new Observer<DqwzBean>() {


            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(DqwzBean dqwzBean) {
                recordId = dqwzBean.getResult().getRecordId();
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void initData() {
        Intent intent = getIntent();
        //获取医生极光账号
        doctorUserName = intent.getStringExtra("doctorUserName");
        String doctorName = intent.getStringExtra("DoctorName");
        tv_consult_name.setText(doctorName);
        //获取医生id
        id = intent.getIntExtra("id", 0);
        try {
            //RSA解密
            ddd = RsaCoder.decryptByPublicKey(doctorUserName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //点击发送
        img_fasong.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                s = et_context.getText().toString();
                MyMessageBean myMessageBean2 = new MyMessageBean();
                myMessageBean2.setContext(s);
                myMessageBean2.setType(1);
                list.add(myMessageBean2);
                advisoryPageMessageAdapter.notifyDataSetChanged();
                //发送极光消息
                singleConversation = Conversation.createSingleConversation(ddd);
                Message message = JMessageClient.createSingleTextMessage(ddd,APP_KEY, s);
                JMessageClient.sendMessage(message);
                message.setOnSendCompleteCallback(new BasicCallback() {
                    @Override
                    public void gotResult(int i, String s) {
                        if (i == 0){
                            Log.e("TAG", "文字发送成功");
                        }else {
                            Log.e("TAG", "文字发送失败");
                        }
                    }
                });
                //调用接口发送
                initFs();
                //清空edittext
                et_context.setText("");
            }
        });

    }
    //本地发送消息
    private void initFs() {
        RetrofitManager.getInstance().postSendData(recordId, s, 1, id, new Observer<SendMessageBean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(SendMessageBean sendMessageBean) {
                if (sendMessageBean.getStatus().equals("0000")){
                    Log.e("TAG", "本地发送成功" );

                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        JMessageClient.unRegisterEventReceiver(this);
    }



    //用户在线期间收到的消息都会以MessageEvent的方式上抛
    public void onEvent(MessageEvent event) {
        Message msg = event.getMessage();
        switch (msg.getContentType()) {
            case text:
                //处理文字消息
                TextContent textContent = (TextContent) msg.getContent();
                String text = textContent.getText();

                MyMessageBean myMessageBean = new MyMessageBean();
                myMessageBean.setContext(text);
                myMessageBean.setType(2);
                list.add(myMessageBean);
                advisoryPageMessageAdapter.notifyDataSetChanged();
                break;
            case image:
                //处理图片消息
                ImageContent imageContent = (ImageContent) msg.getContent();
                String localPath = imageContent.getLocalPath();//图片本地地址
                String localThumbnailPath = imageContent.getLocalThumbnailPath();//图片对应缩略图的本地地址
                
                break;
            case voice:
                //处理语音消息
                VoiceContent voiceContent = (VoiceContent) msg.getContent();
                voiceContent.getLocalPath();//语音文件本地地址
                voiceContent.getDuration();//语音文件时长
                break;
            case custom:
                //处理自定义消息
                CustomContent customContent = (CustomContent) msg.getContent();
                customContent.getNumberValue("custom_num"); //获取自定义的值
                customContent.getBooleanValue("custom_boolean");
                customContent.getStringValue("custom_string");
                break;
            case eventNotification:
                //处理事件提醒消息
                EventNotificationContent eventNotificationContent = (EventNotificationContent)msg.getContent();
                switch (eventNotificationContent.getEventNotificationType()){
                    case group_member_added:
                        //群成员加群事件
                        break;
                    case group_member_removed:
                        //群成员被踢事件
                        break;
                    case group_member_exit:
                        //群成员退群事件
                        break;
                    case group_info_updated://since 2.2.1
                        //群信息变更事件
                        break;
                }
                break;
            case unknown:
                // 处理未知消息，未知消息的Content为PromptContent 默认提示文本为“当前版本不支持此类型消息，请更新sdk版本”，上层可选择不处理
                PromptContent promptContent = (PromptContent) msg.getContent();
                promptContent.getPromptType();//未知消息的type是unknown_msg_type
                promptContent.getPromptText();//提示文本，“当前版本不支持此类型消息，请更新sdk版本”
                break;
        }
    }

    //用户离线期间收到的消息会以OfflineMessageEvent的方式上抛，处理方式类似上面的
    //MessageEvent
    public void onEvent(OfflineMessageEvent event) {
        List<Message> msgs = event.getOfflineMessageList();
        for (Message msg:msgs) {

        }
    }

    
    @TargetApi(19)
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch(event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                recoderUtils.verifyAudioPermissions(ConsultActivity.this);
                recoderUtils.startRecord();
                downT = System.currentTimeMillis();
                recoderDialog.showAtLocation(v, Gravity.CENTER, 0, 0);
                btn_context.setTextColor(Color.WHITE);
                btn_context.setText("松开发送");
                btn_context.setBackgroundResource(R.drawable.shape_recoder_btn_recoding);
                return true;
            case MotionEvent.ACTION_UP:
                recoderUtils.stopRecord();
                recoderDialog.dismiss();
                btn_context.setText("按住说话");
                btn_context.setTextColor(this.getResources().getColor(R.color.blue));
                btn_context.setBackgroundResource(R.drawable.shape_recoder_btn_normal);
                return true;
        }
        return true;
    }

    final int[] voice_time = {0};

    @Override
    public void onUpdate(double db, long time) {
        if(null != recoderDialog) {
            int level = (int) db;
            recoderDialog.setLevel((int)db);
            recoderDialog.setTime(System.currentTimeMillis() - downT);
            voice_time[0] =(int) time;
        }
    }

    @Override
    public void onStop(String filePath) {
        try {
            String doctorUserName = RsaCoder.decryptByPublicKey(this.doctorUserName);
            //语音消息
            Message singleVoiceMessage = JMessageClient.createSingleVoiceMessage(doctorUserName,APP_KEY, new File(filePath), voice_time[0]);
            JMessageClient.sendMessage(singleVoiceMessage);
            singleVoiceMessage.setOnSendCompleteCallback(new ImageContent.CreateImageContentCallback() {
                @Override
                public void gotResult(int i, String s, ImageContent imageContent) {
                    if (i==0){
                        Log.e("TAG", "gotResult: "+"语音发送成功" );
                        MyMessageBean myMessageBean = new MyMessageBean();
                        myMessageBean.setFile(filePath);
                        myMessageBean.setType(4);
                        myMessageBean.setTime(voice_time);
                        list.add(myMessageBean);
                        advisoryPageMessageAdapter.notifyDataSetChanged();
                    }else {
                        Log.e("TAG", "gotResult: "+"语音发送失败" );
                    }
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}